var app = getApp();
const pageSize = 20;
Page({
  data: {
    loadmore: true,
    equipment_id: '',
    eqDetail: {},
    modal: false,
    drawer: false,
    connections: [],
    empty: false,
    navigation_icon: '/images/navigation.png',
    currentTab: 0,
    isReplace: false,
    replace_number: "",
    isRepair: false, //维修员
    isFranchiser: false, //合伙人帮加盟商
    equipment_number: '',
    switchgearContent: '',
  },


  onLoad: function (options) {
    if (options.equipment_id) {
      this.setData({
        equipment_id: options.equipment_id,
        isRepair: options.is_repair == 1 ? true : false,
        isFranchiser: options.is_franchiser == 1 ? true : false,
      })
      this.getEquipment(options.equipment_id)
    }
  },


  navReplaceRecord() {
    let url = 'replaceRecord?equipment_number=' + this.data.eqDetail.equipment_info[this.data.currentTab].equipment_number;
    if (this.data.isRepair) {
      url += "&is_repair=1"
    }
    wx.navigateTo({
      url
    })
  },

  //点击替换主板按钮
  handleReplace() {
    this.setData({
      isReplace: true
    })
  },

  //modal 输入框监听input
  handleInputRepalaceNumber(e) {
    this.setData({
      replace_number: e.detail.value
    })
  },

  scanDeviceCode() {
    app.scanDeviceCode().then(res => {
      this.setData({
        replace_number: res
      })
    }).catch(e => {})
  },

  //确认替换
  replaceConfirm() {
    if (this.data.replace_number == '') {
      app.showToast("请填写主板编号");
      return false;
    }
    wx.showModal({
      title: '提示',
      content: '是否替换主板编号？',
      success: res => {
        if (res.confirm) {
          wx.showLoading({
            title: '替换中',
            mask: true
          })
          let url = "Partner/Equipment/replaceNumber";
          if (this.data.isRepair) {
            url = "Manage/Equipment/replaceNumber";
          }
          app.ajax({
            url,
            data: {
              equipment_number: this.data.eqDetail.equipment_info[this.data.currentTab].equipment_number,
              new_number: this.data.replace_number
            },
            success: result => {
              wx.hideLoading();
              if (result.data.code > 0) {
                app.showToast(result.data.message, "success");
                this.setData({
                  replace_number: "",
                  isReplace: false,
                })
                this.getEquipment(this.data.equipment_id);
              } else {
                app.showToast(result.data.message);
              }
            },
            error: e => {
              app.showToast("网路错误")
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  //取消替换
  replaceCancel() {
    this.setData({
      isReplace: false,
      replace_number: '',
    })
  },

  onPullDownRefresh: function () {
    this.getEquipment(this.data.equipment_id)
  },


  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentTab: index
    })
  },

  swiperChange(e) {
    this.setData({
      currentTab: e.detail.current
    })
  },

  //获取信息
  getEquipment(equipment_id) {
    let url = "Partner/Equipment/detail";
    if (this.data.isRepair) {
      url = "Manage/Equipment/detail";
    }
    app.ajax({
      url,
      data: {
        equipment_control_id: equipment_id
      },
      success: res => {
        if (res.data.code == 1000) {
          console.log(res.data.data);
          this.setData({
            eqDetail: res.data.data
          });
          // var eqDetail = res.data.data;
          // that.setData({
          //   eqDetail,
          //   equipment_switchgear: eqDetail.equipment_status_data.equipment_switchgear
          // })
        } else {
          app.showToast(res.data.msg);
        }
        wx.stopPullDownRefresh()
      }
    })
  },


  deleteDevice(e) {
    wx.showModal({
      content: "确定删除本台设备？",
      success: results => {
        if (results.confirm) {
          wx.showLoading({
            mask: true,
          })
          app.ajax({
            url: 'Partner/Equipment/del',
            data: {
              equipment_control_id: this.data.equipment_id,
            },
            success: res => {
              wx.hideLoading();
              if (res.data.code == 1000) {
                app.showToast(res.data.message, "success");
                setTimeout(() => {
                  let pages = getCurrentPages();
                  let targetPage = pages[pages.length - 2];
                  targetPage.reloadData();
                  wx.navigateBack();
                }, 1500)
              } else {
                app.showToast(res.data.message)
              }
            },
            error: e => {
              wx.hideLoading();
              app.showToast("服务器异常");
            }
          })
        }
      }
    })
  },


  //设备导航
  goMap(e) {
    let lat = e.currentTarget.dataset.lat;
    let lng = e.currentTarget.dataset.lng;
    wx.navigateTo({
      url: '../equipmentMap/equipmentMap?lat=' + lat + '&lng=' + lng,
    })
  },

  filterCoreChange(e) {

    wx.navigateTo({
      url: "../../../engineering/pages/filterCoreRecord/filterCoreRecord?eq_sn=" + e.currentTarget.dataset.equipment_number
    })
  },

  changeSwitch(e) {
    const {
      status,
      number,
      index,
      switchgear,
      type
    } = e.currentTarget.dataset;
    if (status == 2) {
      app.showToast("抱歉！设备已离线");
      return;
    }
    if(type==1){
      this.setData({
        switchgearContent: switchgear == 1 ? '是否开机？' : '是否关机？',
        modal: true
      })
    }else if(type==2){
      this.setData({
        switchgearContent: switchgear == 0 ? '是否开门？' : '是否关门？',
        modal: true
      })
    }
    
    this.switchType=type;//1开关机 2开关门
    this.eq_num = number;
    this.eq_index = index;
    this.switchgear = switchgear;
  },

  handleModalClick(e) {
    console.log(e);
    if (e.detail.index == 1) {
      wx.showLoading();
      let url,upData;
      //1开关机 2开关门  
      if(this.switchType==1){
          url = this.data.isRepair?"Manage/Equipment/switchgear":"Partner/Equipment/switchgear";
          upData={
            sn: this.eq_num,
            val: this.switchgear == 1 ? 2 : 1,
          }
      }else if(this.switchType==2){
        url="Common/Equipment/controlDoor";
        upData={
          sn: this.eq_num,
          status: this.switchgear == 1 ? 0 : 1,
        }
      }
      app.ajax({
        url,
        data: upData,
        success: res => {
          wx.hideLoading();
          this.hideModal();
          if (res.data.code == 1000) {
            app.showToast(res.data.message, "success");
            if(this.switchType==1){
              this.setData({
                [`eqDetail.equipment_info[${this.eq_index}].equipment_status_data.equipment_switchgear`]: this.switchgear == 1 ? 2 : 1
              })
            }else{
              this.setData({
                [`eqDetail.equipment_info[${this.eq_index}].door_status`]: this.switchgear == 1 ? 0 : 1
              })
            }
           
            delete(this.eq_num);
            delete(this.eq_index);
            delete(this.switchgear);
            delete(this.switchType);
          } else {
            app.showToast(res.data.message)
          }
        },
        error: e => {
          wx.hideLoading();
        }
      })
    } else {
      this.hideModal();
      delete(this.eq_num);
      delete(this.eq_index);
      delete(this.switchgear);
      delete(this.switchType);
    }

  },

  hideModal() {
    this.setData({
      modal: false
    })
  },

  //连接记录
  connectRecord(e) {
    var that = this;
    this.page = 1;
    this.equipment_number = e.currentTarget.dataset.equipment_number;
    that.setData({
      equipment_number: this.equipment_number
    })
    this.getConnectRecord();
  },

  getConnectRecord() {
    app.ajax({
      url: "Partner/Equipment/connection",
      data: {
        "page": this.page,
        "pageSize": pageSize,
        "equipment_number": this.equipment_number
      },
      success: res => {
        if (res.data.code > 0) {
          const {
            count,
            connection: source
          } = res.data.data;
          let connections = this.data.connections.concat(source);
          this.setData({
            empty: count == 0 ? true : false,
            connections,
            loadmore: connections.length < count ? true : false,
            nomore: connections.length >= count ? true : false,
            drawer: true
          })
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误");
      }
    })
  },

  loadingConnection() {
    if (this.data.loadmore) {
      this.page = this.page + 1;
      this.getConnectRecord();
    }
  },

  closeDrawer() {
    this.setData({
      drawer: false,
      connections: [],
      empty: false,
      loadmore: false,
      nomore: false
    })
    delete(this.page);
    delete(this.equipment_number)
  },

  consumeHistory(e) {
    wx.navigateTo({
      url: '../coresChange/coresChange?equipment_number=' + e.currentTarget.dataset.equipment_number,
    })
  },

  //跳转到设备二维码
  navDeviceQrcode(e) {
    wx.navigateTo({
      url: 'deviceQrcode?eq_sn=' + e.currentTarget.dataset.equipment_number,
    })
  },


  //跳转售水参数修改
  navSellingWater(e) {
    wx.navigateTo({
      url: '../parameter/sellingWater?eq_sn=' + e.currentTarget.dataset.equipment_number,
    })
  },

  //跳转设备状态
  navDeviceStatus(e) {
    let url = 'deviceStatus?equipment_number=' + e.currentTarget.dataset.equipment_number;
    if (this.data.isRepair) {
      url += "&is_repair=1"
    }
    wx.navigateTo({
      url,
    })
  },

  //跳转制水参数修改
  navMakingWater(e) {
    wx.navigateTo({
      url: '../parameter/makingWater?eq_sn=' + e.currentTarget.dataset.equipment_number,
    })
  },
  //跳转控制参数修改
  navControlParameter(e) {
    wx.navigateTo({
      url: '../parameter/controlParameter?eq_sn=' + e.currentTarget.dataset.equipment_number,
    })
  },
  //跳转系统参数修改
  navSystemParameter(e) {
    wx.navigateTo({
      url: '../parameter/systemParameter?eq_sn=' + e.currentTarget.dataset.equipment_number,
    })
  },
  ///跳转用户列表
  userList(e) {
    wx.navigateTo({
      url: '../userList/userList?equipment_id=' + e.currentTarget.dataset.equipment_id,
    })
  },
})